/*
 * @author java_deng
 * @date 2025/2/5 12:29
 * @description
 */
package org.hbwl.controller;

import org.hbwl.dto.Image;
import org.hbwl.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@RestController
@RequestMapping("/image")
public class ImageController extends BaseController{
    @Autowired
   private ImageService imageService;

    @GetMapping("/swiperList")
    public Object swiperList(){
        return  success(imageService.swiperList());
    }

    @PostMapping("/uploadSwiper")
    public Object upload(@RequestParam("file") MultipartFile file){
        Long save = save(file,"swiper");
        if(save==0){
            return fail(new String("上传的文件类型错误,只能上传png,jpeg,jpg类型的文件"));
        }
        return success(save);
    }

    @PostMapping("/uploadImage")
    public Object uploadImage(@RequestParam("file") MultipartFile file){
        Long save = save(file,"image");
        if(save==0){
            return fail(new String("上传的文件类型错误,只能上传png,jpeg,jpg类型的文件"));
        }
        return success(save);
    }


    private Long save(MultipartFile file,String type){
        String originName = file.getOriginalFilename();
        Set<String> set = new HashSet<>();
        set.add(".png");
        set.add(".jpeg");
        set.add(".jpg");
        int count = 0;
        for(int i = 0; i < originName.length(); i++){
            if(originName.charAt(i) == '.'){
                count = i;
                break;
            }
        }
        String endName = originName.substring(count);
        String randomName=Double.toString(Math.random()).substring(2,6);
        String fileType = originName.substring(count + 1);
        if(!set.contains(endName)){
            return 0L;
        }
        try {
            String name=System.currentTimeMillis()+randomName+endName;
            String path="D:\\codeSoft\\nginx\\nginx-1.26.3\\html\\"+type+"\\"+name;
            file.transferTo(new File(path));
            Image image=new Image();
            image.setPath("http://localhost:80/"+type+"/"+name);
            image.setTitle(originName);
            image.setType(type.equals("swiper")?1:2);
            image.setStatus(1);
            imageService.save(image);
            return image.getId();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
